<!--
 * @Author: lirl
 * @Date: 2024-05-27 10:23:24
 * @Description: 流程整合起草模板
-->
<template>
  <div v-loading="pageLoading">
    <business-quickly-draft
      ref="templateRef"
      v-if="identityId && showDraftPage"
      :drafterIdentityId="`${identityId}`"
      :bizCompositeTypeCode="bizCompositeTypeCode"
      :bizTaskTitle="processTitle"
      :secret="secret"
      :attachmentAreaSpaceCode="bizFormConfig.attachmentAreaSpaceCode"
      :attachmentAccept="bizFormConfig.attachmentAccept"
      :collapseList="bizFormConfig.collapseList"
      :attachmentRemark="attachmentRemark"
      :docData="docData"
      :pathVarData="pathVarData"
      :candidateVarData="candidateVarData"
      :bizProcessTemplateAttrs="settings.templateAttrs"
      :bizProcessSubmitAttrs="settings.processSubmitAttrs"
      :enableDbClickPreview="enableDbClickPreview"
      :defaultAddDocAttachment="defaultAddDocAttachment"
      :clearDocAttAfterSettingBackToBack="clearDocAttAfterSettingBackToBack"
      :importantSecretDownLoad="importantSecretDownLoad"
      :bizBudgeInfoOrgCodeLevel="bizBudgeInfoOrgCodeLevel"
      :uploadRequestHeaders="uploadRequestHeaders"
      :emptyOpinionCollapse="emptyOpinionCollapse"
      :prodDisplayWatermark="prodDisplayWatermark"
      :documentTitles="templateNames"
      :bizOpinionAttrs="settings.opinionAttrs"
      :biz-form-data="bizFormData"
      :getBizFormData="getBizFormData"
      :getDownloadFileTitleFunc="bizDownloadFileTitleFunc"
      :bizSaveFunction="bizSaveFunction"
      :bizAfterSave="bizAfterSave"
      :bizBeforePathNext="bizBeforePathNext"
      :bizBeforeTaskSubmit="bizBeforeTaskSubmit"
      :bizAfterTaskSubmit="bizAfterTaskSubmit"
      :bizAfterClose="bizAfterClose"
      :bizBeforeSubmitParam="bizBeforeSubmitParam"
      :bizBeforeClickSubmitBtn="bizBeforeClickSubmitBtn"
      :bizBeforeClickCancel="bizBeforeClickCancel"
      :bizBeforeCancel="bizBeforeCancel"
      :bizAfterCancel="bizAfterCancel"
      :upload-multi-domain-collapse-list="bizFormConfig.uploadMultiDomainCollapseList"
      :useOverflowPreview="useOverflowPreview"
      :useUploadMultiDomain="bizFormConfig.useUploadMultiDomain"
      :showSingleDomainFileNum="showSingleDomainFileNum"
      :show-content-of-attachment-area="showContentOfAttachmentArea"
      @setAllFieldsReadonly="setAllFieldsReadonly"
      @afterLoadDocEditor="afterLoadDocEditor"
      @bizProcessInit="bizProcessInit"
      @doAction="doAction"
      @commonEvent="templateCommonEvent"
      @saveNumber="saveNumber"
    >
    <template v-slot:baseInfo="slotProps">
      <component
        ref="subform"
        v-if="!isEmpty(slotProps.configData)"
        :is="subFormComponent"
        v-bind="slotProps"
        :process-title.sync="processTitle"
        :formAttrs="formAttrs"
        :validate-by-alert="validateByAlert"
        :all-fields-readonly="allFieldsReadonly"
        :login-user-info="{ treeId, telphone, loginName }"
        :need-save-datas="needSaveDatas"
        @changeSecret="changeSecret"
        @changeAttachmentRemark="changeAttachmentRemark"
        @pathVarData="getPathVarData"
        @candidateVarData="getCandidateVarData"
        @setDocData="setDocData"
        @commonEvent="commonEvent"
        @afterLoadForm="afterLoadSubForm"
      ></component>
      </template>
    </business-quickly-draft>
    <jdf-select-identity
      ref="selectIdentity"
      v-model="identityId"
      :identity-list="identityList"
      notice-text="请选择人员身份"
      @choose="selectIdentityConfirm"
    ></jdf-select-identity>
  </div>
</template>

<script>
import { UserIdentityService } from 'jdf-jssdk';
import { isEmpty, isObject } from 'lodash-es';
import { closeWindow } from 'jdf-util';
import { bizServiceURL } from '@/api/utils/constants';
import { alertErrorMsg } from '@/api/utils/pc-message';
import { templateNames } from '@/utils/enum';
import settings from '@/settings/settings';
import subFormConfig from './subFormConfig.json';
import processFormCommonMixin from './processFormCommonMixin';

export default {
  name: 'ProcessCompositeDraft',
  mixins: [processFormCommonMixin],
  data() {
    return {
      isEmpty,
      templateNames,
      settings,
      pageLoading: false,
      // 流程融合类型编码
      bizCompositeTypeCode: this.$route.query.bizCompositeTypeCode,
      // 当前人可选身份列表
      identityList: [],
      // 起草使用的身份id
      identityId: '',
      // 是否显示起草页面
      showDraftPage: false,
      // 自定义业务表单模板配置
      bizFormConfig: {},
      // 当前选中的业务流程的流程配置信息
      configData: {},
      // 当前选中的业务流程的配置信息
      businessInfo: {},
      // 要加载的子组件
      subFormComponent: null,
      // 不显示表单提交区域
      formSubmit: false,
      // 是否使用悬浮预览
      useOverflowPreview: true,
      // 是否展示单个附件域计数
      showSingleDomainFileNum: false,
      // 是否展示正文附件域
      showContentOfAttachmentArea: false,
    };
  },

  created() {
    // 获取存储的起草人身份id，如果有，则不需要再选身份
    const identityId = sessionStorage.getItem('composite-drafter-identityId');
    if (identityId) {
      this.identityId = identityId;
      this.showDraftPage = true;
    } else {
      this.draft();
    }
  },
  methods: {
    /**
     * 起草
     */
    async draft() {
      try {
        this.pageLoading = true;
        // 获取当前人身份列表
        const identityList = await new UserIdentityService(bizServiceURL).getByLoginName(this.loginName);
        // 如果没有身份，则弹出提示
        if (isEmpty(identityList)) {
          this.$alert('未获取到起草人身份', '提示', {
            type: 'warning',
            callback: () => {
              closeWindow(false);
            }
          });
          return;
        }
        // 如果只有一个身份，则直接起草
        if (identityList.length === 1) {
          const [{ id }] = identityList;
          this.identityId = id;
          this.showDraftPage = true;
        } else {
          // 如果有多个身份，则弹出选身份窗口
          this.identityList = identityList;
          this.$refs.selectIdentity.show();
        }
      } catch (error) {
        alertErrorMsg(error);
      } finally {
        this.pageLoading = false;
      }
    },
    /**
     * 选择身份
     */
    selectIdentityConfirm() {
      this.showDraftPage = true;
    },
    /**
     * 根据配置规则加载子组件
     */
    loadSubComponent() {

    },
    /**
     * 业务流程初始化成功事件，根据业务流程编码获取要加载的表单业务组件及配置信息
     */
    bizProcessInit({ configData, bizInfo, reloadSubform = true }) {
      this.configData = configData;
      this.businessInfo = bizInfo;
      if (!reloadSubform) {
        return;
      }
      // 根据业务流程编码匹配要加载的子组件
      const config = subFormConfig[bizInfo.businessCode];
      // 要加载的表单业务组件
      this.subFormComponent = resolve => require([
        `@/views/procecss-form${isObject(config.form) ? config.form[bizInfo.flowVer] : config.form}`
      ], resolve);
      this.bizFormConfig = config;
    },
    /**
     * 保存后置
     */
    bizAfterSave() {
      return this.$refs.subform.builtInAfterSave?.();
    },
  }
};

</script>
